/*
 * @Author: blak-kong
 * @Date: 2019-12-03 09:51:44
 * @Email: 546598185@qq.com
 */

const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const keys = require('../config/keys');

// models
const User = require('../models/user');
const { SuccessModel, ErrorModel } = require("../models/resModel")


module.exports = {
    // 注册用户
    async register (ctx, next) {
        // 查询数据库中是否存在用户名
        let name = ctx.request.body.name
        let newUser = new User({
            name: ctx.request.body.name,
            realname: ctx.request.body.realname,
            password: ctx.request.body.password,
            identity: ctx.request.body.identity
        })
        let res = await User.findOne({ name })
        if (res) {
            ctx.body =  new ErrorModel({}, '用户名已注册!')
            return
        } else {
            let salt = await bcrypt.genSalt(10)
            let hash = await bcrypt.hash(newUser.password, salt)
            newUser.password = hash;

            let user = await newUser.save()
            if (user) {
                ctx.body =  new SuccessModel({
                    user,
                    success: true
                })
                return
            }
        }
    },
    // 登录用户
    async login (ctx, next) {
        const name = ctx.request.body.name
        const password = ctx.request.body.password

        // 查询数据库
        let res = await User.findOne({ name })
        if (!res) {
            ctx.body =  new ErrorModel({}, '用户不存在!')
            return
        }

        // 密码匹配
        let isMatch = await bcrypt.compare(password, res.password)
        if (isMatch) {
            const rule = {
                id: res.id,
                name: res.name,
                identity: res.identity
            };
            let token = jwt.sign(rule, keys.secretOrKey, { expiresIn: 3600 })
            if (token) {
                ctx.body = new SuccessModel({
                    success: true,
                    token: 'Bearer ' + token
                })
                return
            }
        }
        ctx.body =  new ErrorModel({}, '密码错误!')
        return
    }
}